<template>
  <t-dialog
    v-model:visible="show"
    :width="900"
    :header="plugin.t('reverse_ticket.title')"
    destroyOnClose
    :closeOnOverlayClick="false"
    placement="center"
    class="plugin-miravia-order-ticket"
  >
    <template #body>
      <div class="content">
        <t-alert class="alert" theme="info">
          <span v-for="alert in plugin.tm('reverse_ticket.alert')">{{ alert }}</span>
        </t-alert>
        <t-row :gutter="20">
          <t-col :span="3">
            <div class="bg-box">
              <div class="item wrap">
                <div class="name">{{ plugin.t('reverse_ticket.total') }}</div>
                <span>{{ table.total }}</span>
              </div>
            </div>
          </t-col>
          <t-col :span="3">
            <div class="bg-box">
              <div class="item wrap">
                <div class="name">{{ plugin.t('reverse_ticket.ready') }}</div>
                <span class="color">{{ table.ready }}</span>
              </div>
            </div>
          </t-col>
          <t-col :span="3">
            <div class="bg-box">
              <div class="item wrap">
                <div class="name">{{ plugin.t('reverse_ticket.warning') }}</div>
                <span class="warning">{{ table.warning }}</span>
              </div>
            </div>
          </t-col>
          <t-col :span="3">
            <div class="bg-box">
              <div class="item wrap">
                <div class="name">{{ plugin.t('reverse_ticket.ok') }}</div>
                <span class="success">{{ table.ok }}</span>
              </div>
            </div>
          </t-col>
        </t-row>
        <t-table
          row-key="id"
          table-layout="auto"
          :data="table.data"
          :columns="table.columns"
          :loading="table.loading"
          maxHeight="40vh"
          bordered
          size="small"
        >
          <template #right="{ row }">
            <t-icon v-if="row.response_icon == 'ready'" name="link-1" style="color: var(--td-brand-color)"/>
            <t-icon v-if="row.response_icon == 'loading'" name="loading" style="color: var(--td-brand-color)"/>
            <t-icon v-if="row.response_icon == 'success'" name="check-circle" style="color: var(--td-success-color)"/>
            <t-icon v-if="row.response_icon == 'warning'" name="error-circle" style="color: var(--td-warning-color)"/>
          </template>
        </t-table>
      </div>
    </template>
    <template #footer>
      <t-button theme="primary" v-if="!loading" :disabled="table.total != table.ready" @click="onSubmit">
        {{ plugin.t('reverse_ticket.button') }}
      </t-button>
      <t-progress theme="plump" :percentage="progress" status="active" v-else />
    </template>
  </t-dialog>
</template>
<script setup>
  import { ref, reactive } from 'vue'
  import app from '@/app'
  import index from '../../index'
  import { ticket } from '@/api/provider/miravia_reverse'
  import { post as payPost } from '@/api/store/order_pay'
  import reverseStore from '../../store/reverse'
  import createStore from '@/plugin/order/views/create/store'

  const plugin = index.plugin

  const show = ref(false)
  const loading = ref(false)
  const progress = ref(0)
  const table = reactive({
    data: [],
    loading: false,
    warning: 0,
    ready: 0,
    total: 0,
    ok: 0,
    columns: [{
      title: plugin.t('reverse.number'),
      colKey: 'number',
      width: 160
    }, {
      title: plugin.t('reverse.order_number'),
      colKey: 'order_number',
      width: 160
    },{
      title: plugin.t('reverse_ticket.response'),
      colKey: 'response'
    }, {
      colKey: 'right',
      align: 'center',
      cell: 'right',
      width: 50
    }]
  })

  const open = async () => {
    show.value = true

    if(!loading.value) {
      await updateItem(reverseStore.selectData)
      reverseStore.selectEmpty()
    }
  }

  const updateItem = async (orders) => {
    if(!orders.length) return
    table.loading = true
    table.data = orders
    table.ready = 0
    table.warning = 0
    table.total = orders.length

    try{
      // 拉取详情和关联商品
      await reverseStore.goods(orders)

      // 循环订单
      table.data.forEach(order => {
        // 检查订单
        if(orderCheck(order)) {
          table.ready += 1
        } else {
          table.warning += 1
        }
      })
    } catch(e) {
      app.message('warning', plugin.message('reverse_ticket.message.error.item'))
    }
    table.loading = false
  }

  // 检查订单
  const orderCheck = (order) => {
    // 是否开通过发票
    if(order.ticket) {
      orderResponse(order, 'warning', 'error.ticket', order)
      return false
    }

    // 检测原订单是否开过发票
    if(!order.order || !order.order.ticket) {
      orderResponse(order, 'warning', 'error.on_ticket', order)
      return false
    }
    
    if(!order.goods) {
      orderResponse(order, 'warning', 'error.check_goods', order)
      return false
    } else {
      orderResponse(order, 'ready', 'ready')
      return true
    }
  }

  // 订单状态
  const orderResponse = (order, status, lang, data = {}) => {
    order.response = plugin.t('reverse_ticket.message.' + lang, data)
    order.response_icon = status
  }

  const onSubmit = async () => {
    loading.value = true
    // 初始化
    await createStore.init()

    try{
      for (let index = 0; index < table.data.length; index++) {
        const order = table.data[index]
        orderResponse(order, 'loading', 'loading')
        // 开始创建发票
        orderResponse(order, 'success', 'ok', await create(order))
        table.ok += 1
        table.ready -= 1
      }
    } catch(e) {
      console.error(e)
      app.message('warning', plugin.message('reverse_ticket.message.error.create'))
    }

    await reverseStore.get()
    loading.value = false
  }

  // 创建发票
  const create = async (order) => {
    // 生成商品
    const goods = createStore.make({
      ...order.goods,
      name: order.name,
      price: order.money
    })
    // 退款商品要负数
    goods.count = -1
    // 生成商品附加到收银台中
    createStore.initData({
      ticket: 'print_refund',
      code_key: order.order.ticket,
      remarks: 'Miravia ' + order.number
    }, [goods])
    // 收银台更新数据
    createStore.update()

    // 收回数据
    const data = createStore.getData()

    // 创建订单发票
    const orderTicket = await createStore.postTicket(false)

    // 支付
    await payPost(orderTicket.id, {
      pay_money: data.money,
      pay_change: 0,
      pay_status: 1,
      data: [{
        pay_id: -1, 
        pay_name: 'Miravia',
        money: data.money,
      }]
    })

    // 更新
    await ticket(order.id, orderTicket.code)

    return orderTicket
  }

  defineExpose({ open })
</script>
<style lang="scss">
  @import '@/style/global';

  .plugin-miravia-order-ticket{
    overflow: hidden;

    @include table-size(12px);

    .bg-box{
      padding: 20px !important;
    }

    .content{
      overflow: hidden;
    }

    .t-dialog{
      background-color: $color-bg;
    }

    .alert{
      margin-bottom: 25px;
      span{
        display: block;
        line-height: 25px;
      }
    }

    .item{  
      color: $color-title;
      font-size: 16px;
      line-height: 20px;
      
      .name{
        color: $color-body;
        padding-bottom: 10px;
        font-size: 14px;
      }

      span{
        font-weight: bold;
      }

      .color{
        color: $color;
      }
      .warning{
        color: $color-warning;
      }
      .success{
        color: $color-success;
      }
    }
  }
</style>